﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SchoolLibrary.Entity.Person;
using SchoolLibrary.Entity;

namespace SchoolLibrary.DataBase.DAO
{
    public class PupilDAO : AbstractDAO<Pupil>
    {
        private static PupilDAO instance;

        private PupilDAO() { }

        public static PupilDAO getInstance()
        {
            if (instance == null)
            {
                instance = new PupilDAO();
            }
            return instance;
        }

        public override Pupil findById(long id)
        {
            Query classQuery = new Query(Pupil.FIND_BY_ID);
            classQuery.setParameter("id", id);
            return getDAOHelper().getSingleResult(classQuery);
        }

        public override List<Pupil> findAll()
        {
            Query classQuery = new Query(Pupil.FIND_ALL);
            return getDAOHelper().getResultList(classQuery);
        }

        public override void save(Pupil pupil)
        {
            if (pupil.Id != UNDIFINED_ID)
            {
                save(pupil, Pupil.UPDATE_PUPIL);
            }
            else
            {
                save(pupil, Pupil.SAVE_PUPIL);
            }
        }

        private void save(Pupil pupil, string queryString)
        {
            Query query = new Query(queryString);
            query.setParameter("id", pupil.Id);
            query.setParameter("name", pupil.Name);
            query.setParameter("middleName", pupil.MiddleName);
            query.setParameter("surname", pupil.Surname);
            query.setParameter("classId", pupil.PupilClass.Id);
            getDAOHelper().executeUpdate(query);           
        }

        public List<Pupil> findBookHoldersByClass(Class selectedClass)
        {
            Query query = new Query(Pupil.FIND_BOOK_HOLDERS_BY_CLASS_ID);
            query.setParameter("classId", selectedClass.Id);
            return getDAOHelper().getResultList(query); 
        }
    }
}
